﻿using System.Data.Entity;
using System.Net.Sockets;
using System.Security.Cryptography;
using BizModels;
using DataModel;
using IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Repositories
{
    public class MemberRepository : RepositoryBase, IMemberRepository
    {
        public int GetLogin(string userId, string userPwd)
        {
            Context = new HinokyEntities();

            var userInfo = Context.Members.FirstOrDefault(s => s.Id.Equals(userId) && s.Password.Equals(userPwd));

            return userInfo == null ? 0 : userInfo.UserKey;
        }

        public MemberT GetUserInfo(int userKey)
        {
            Context = new HinokyEntities();

            var userInfo = Context.Members.FirstOrDefault(s => s.UserKey.Equals(userKey));
            if (userInfo != null)
            {
                return new MemberT
                {
                    UserKey = userInfo.UserKey,
                    UserID = userInfo.Id,
                    Name = userInfo.Name,
                    Roles = userInfo.Roles.Select(s => s.RoleId).ToArray()
                };
            }

            return null;
        }

        public MemberT GetUserInfo(string facebookId)
        {
            Context = new HinokyEntities();

            var userKey =
                (from s in Context.FaceBookMembers where s.FaceBookId == facebookId select s.UserKey).FirstOrDefault();

            var userInfo = Context.Members.FirstOrDefault(s => s.UserKey.Equals(userKey));
            if (userInfo != null)
            {
                return new MemberT
                {
                    UserKey = userInfo.UserKey,
                    UserID = userInfo.Id,
                    Name = userInfo.Name,
                    Roles = userInfo.Roles.Select(s => s.RoleId).ToArray()
                };
            }

            return null;
        }

        public int AddMember(MemberT memberInfo)
        {
            var data = new Members
            {
                Id = memberInfo.UserID,
                Password = memberInfo.Password,
                Name = memberInfo.Name
            };

            Context.Members.Add(data);
            return Context.SaveChanges();
        }
    }
}
